package com.hedl.classroom.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.DeleteResponse;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.UpdateResponse;
import com.hedl.classroom.base.exception.OnlinecClassroomException;
import com.hedl.classroom.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @description 课程索引管理接口实现
 * @author Big Watermelon
 * @date 2023/11/02/17:19
 */
@Slf4j
@Service
public class IndexServiceImpl implements IndexService {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    @Override
    public Boolean addCourseIndex(String indexName, String id, Object object) {
        IndexResponse indexResponse = null;
        //添加了这个方法之后进行了，json化；切记这里es后面并不需要我们json数据，es会自动为我们json化
        //String jsonString = JSON.toJSONString(object);
        try {
            indexResponse = elasticsearchClient.index(
                    indexRequest -> indexRequest.index(indexName).id(id).document(object)
            );
        } catch (IOException e) {
            log.error("添加索引出错:{}",e.getMessage());
            e.printStackTrace();
            OnlinecClassroomException.cast("添加索引出错");
        }
        String name = indexResponse.result().name();
        return name.equalsIgnoreCase("created") || name.equalsIgnoreCase("updated");
    }

    @Override
    public Boolean updateCourseIndex(String indexName, String id, Object object) {
        //String jsonString = JSON.toJSONString(object);

        UpdateResponse updateResponse = null;
        try {
            updateResponse = elasticsearchClient.update(u->u.index(indexName).id(id).doc(object),Object.class);
        } catch (IOException e) {
            log.error("更新索引出错：{}",e.getMessage());
            e.printStackTrace();
            OnlinecClassroomException.cast("更新索引出错!");
        }
        // 记得检查这里？
        String name = updateResponse.result().name();
        return name.equalsIgnoreCase("updated");
    }

    @Override
    public Boolean  deleteCourseIndex(String indexName, String id) {
        //响应对象
        DeleteResponse deleteResponse = null;
        try {
            deleteResponse = elasticsearchClient.delete(dr -> dr.index(indexName).id(id));
        } catch (IOException e) {
            log.error("删除索引出错：{}",e.getMessage());
            e.printStackTrace();
            OnlinecClassroomException.cast("删除索引出错!");
        }
        //获取响应结果
        String name = deleteResponse.result().name();
        return name.equalsIgnoreCase("deleted");
    }
}
